import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import Enumerable from 'linq';
import AccountJS from '@/utils/account';
import * as RT from '@/utils/rel';
import * as Util from '@/utils/utils';
import styles from './styles.less';

import { Card, Button, Form, List, Tabs, Popconfirm, Table, message } from 'antd';

import AddInvForm from '../Components/AddInvForm';
import InvEditor from '../Components/InvEditor';

const TabPane = Tabs.TabPane;

const ModelName = 'inv';

@connect(({ loading, faPiaoState, tiDanState, mbl }) => ({
  loading: loading.models[ModelName],
  fps: faPiaoState.list,
  tds: tiDanState.list,
  mbl: mbl.current,
}))
@Form.create()
class Comp extends PureComponent {
  state = {
    addInvVisible: false,
    lockInvVisible: false,

    invList: [],
    recList: [],

    activeKey: '0',
  };

  componentDidMount() {
    const { mbl } = this.props;
    this.setCurrent(mbl);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.mbl !== this.props.mbl) {
      this.setCurrent(nextProps.mbl);
    }
  }

  setCurrent(mbl) {
    if (mbl)
      this.setState({ mbl: mbl }, () => {
        this.reloadData();
      });
  }

  reloadData = () => {
    const { dispatch, mbl } = this.props;

    dispatch({
      type: `${ModelName}/getByBillId`, // 查询一个单及其子单的所有账单
      payload: mbl.id,
      callback: respInv => {
        this.setState({
          invList: respInv,
        });
      },
    });

    dispatch({
      type: `receivable/getReceiptByBillId`, // 收账记录
      payload: mbl.id,
      callback: resp => {
        this.setState({
          recList: resp,
        });
      },
    });

  };

  setActiveKey() {
    const { invList } = this.state;
    let maxId = Math.max.apply(Math, invList.map(o => o.id));
    this.setState({ activeKey: String(maxId) })
  }

  handleDownload = (inv) => {
    if (inv && inv.id && (inv.invoiceType === 1 || inv.invoiceType === 2) > 0) window.open(`/api/inv/ShowInv?invId=${inv.id}`, 'blank');
  };

  // 核销
  handleLockClick = (inv) => {
    if (inv.isLock === 0) {
      this.setState({
        lockInvVisible: true,
        currentInv: inv,
      });
    } else {
      const { dispatch } = this.props;
      dispatch({
        type: `${ModelName}/lockInv`,
        payload: {
          invId: inv.id,
          isLock: 0,
        },
        callback: resp => {
          if (resp)
            this.reloadData();
        },
      });
    }
  };

  // 删除
  handleInvDeleteClick = (inv) => {
    const { dispatch } = this.props;
    dispatch({
      type: `${ModelName}/deleteInv`,
      payload: inv.id,
      callback: () => {
        this.reloadData();
      },
    });
  };

  // 账单核销...提交
  handleLockInvFormSubmit = () => {
    const { dispatch } = this.props;
    const { form } = this.lockInvForm.props;
    const { currentInv } = this.state;

    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      const payload = {
        invId: currentInv.id,
        isLock: 1 - currentInv.isLock,
        lockDate: Util.getChineseDate(values.lockDate),
      };

      dispatch({
        type: `${ModelName}/lockInv`,
        payload: payload,
        callback: resp => {
          if (resp) {
            this.setState({ lockInvVisible: false });
            this.reloadData();
          }
        },
      });
    });
  };

  // 账单新增...提交
  handleAddInvFormSubmit = (vm) => {
    const { dispatch } = this.props;
    console.log("handleAddInvFormSubmit VM:", vm);

    const payload = {
      billId: this.props.mbl.id,
      ...vm,
    };

    dispatch({
      type: `${ModelName}/addInv`,
      payload: payload,
      callback: resp => {
        if (resp) {
          console.log("ADD INV RESP", resp);
          this.reloadData();
          this.setState({
            addInvVisible: false,
            activeKey: String(resp.id),
          });
        }
      },
    });
  };

  // 保存
  handleSaveInvSubmit = (vm) => {
    const { dispatch } = this.props;
    const payload = {
      ...vm,
    };

    dispatch({
      type: `${ModelName}/saveInv`,
      payload: payload,
      callback: resp => {
        if (resp && resp.status == 200) {
          this.reloadData();
          // this.setState({ activeKey: String(resp.id) });
        }
      },
    });
  }

  onChange = (activeKey) => {
    this.setState({ activeKey });
  }

  render() {
    const { loading, mbl } = this.props;
    const { activeKey, addInvVisible, invList, recList } = this.state;

    console.log("REC LIST", recList);

    const actions = (item) => (
      <div>
        <a style={{ marginLeft: '8px', display: item.invoiceType === 1 || item.invoiceType === 2 ? '' : 'none' }} onClick={() => this.handleDownload(item)}>下载</a>
        <Popconfirm title="确定要删除吗?" onConfirm={() => this.handleInvDeleteClick(item)}>
          <a style={{ marginLeft: '8px', display: item && item.isLock === 1 ? 'none' : '' }}>删除</a>
        </Popconfirm>
      </div>
    );

    return (
      <Card className={styles.card} >
        <Tabs
          onChange={this.onChange}
          activeKey={activeKey}
          tabBarExtraContent={<Button type="primary" disabled={mbl && mbl.isLock === 1} onClick={() => { this.setState({ addInvVisible: true }) }}>添加</Button>}
          onEdit={this.onEdit}
        >
          {invList.map(item => (
            <TabPane tab={item.relationerName} key={item.id} closable={false}>
              <InvEditor loading={loading} key={item} rec={recList.filter(r => r.invoiceId === item.id)} inv={item} actions={actions(item)} onDelete={this.handleDelete} onSave={this.handleSaveInvSubmit} />
            </TabPane>)
          )}
        </Tabs>
        <AddInvForm
          visible={addInvVisible}
          onOk={(vm) => this.handleAddInvFormSubmit(vm)}
          onCancel={() => this.setState({ addInvVisible: false, })}
        />
      </Card>
    );
  }
}

export default Comp;
